const connect = require('../utils/db_contonct')
const userModel = require('../model/userModel')
const {
    page
} = require('../utils/page')

function userServices() {
    return {
        async add(params) {
            await connect()
            try {
                const data = await userModel.create(params)
                return data
            } catch (error) {
                return new Error(error)
            }
        },
        async edit(params) {
            await connect()
            try {
                const data = await userModel.findByIdAndUpdate({
                    _id: params.id
                }, params)
                return data
            } catch (error) {
                return new Error(error)
            }
        },
        async findById(id) {
            await connect()
            try {
                const data = await userModel.findOne({
                    _id: id
                })
                return data
            } catch (error) {
                return error
            }
        },
        async findAll() {
            await connect()
            try {
                const data = await userModel.find()
                return data
            } catch (error) {
                return error
            }
        },
        async findByPage(params) {
            await connect()
            try {
                const data = await userModel.find({
                    name: new RegExp(params.name, 'i')
                },'name age habbit').limit(params.size).skip(params.size * (params.current - 1)).exec()
                
                return page(data, await userModel.count())
            } catch (error) {
                console.log('error----')
                return new Error(error)
            }
        },
        async findByName(params) {
            await connect()
            try {
                const data = await userModel.find({
                    name: new RegExp(params.name, 'i')
                }).exec()
                return data
            } catch (error) {
                console.log('error----')
                return new Error(error)
            }
        },
        async del(id) {
            await connect()
            try {
                const data = await userModel.findOneAndDelete({
                    _id: id
                })
                return data
            } catch (error) {
                return error
            }
        }
    }
}
module.exports = userServices()